package com.love.marriage.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.love.marriage.common.vo.SecurityUser;
import com.love.marriage.utils.UserUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 *description:  设置新增和修改的默认时间
 *author:       alex
 *createDate:   2021/6/6 15:16
 *version:      1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if (metaObject.hasSetter("isValid")) {
            this.strictInsertFill(metaObject, "isValid", Integer.class, 1);
        }
        if (metaObject.hasSetter("deleteFlag")) {
            this.strictInsertFill(metaObject, "deleteFlag", Integer.class, 0);
        }
        if (metaObject.hasSetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        }
        if (metaObject.hasSetter("operateTime")) {
            metaObject.setValue("operateTime", null);
            this.strictInsertFill(metaObject, "operateTime", LocalDateTime.class, now);
        }
        SecurityUser loginUser = UserUtils.getLoginUser();
        log.info("insertFill loginUser:{}", loginUser);
        Long id = Optional.ofNullable(loginUser).map(SecurityUser::getId).orElse(null);
        if (id != null) {
            if (metaObject.hasSetter("creator")) {
                this.strictInsertFill(metaObject, "creator", Long.class, id);
            }
            if (metaObject.hasSetter("operator")) {
                this.strictInsertFill(metaObject, "operator", Long.class, id);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        if (metaObject.hasSetter("operateTime")) {
            metaObject.setValue("operateTime", null);
            this.strictUpdateFill(metaObject, "operateTime", LocalDateTime.class,  now);
        }
        SecurityUser loginUser = UserUtils.getLoginUser();
        log.info("insertFill loginUser:{}", loginUser);
        Long id = Optional.ofNullable(loginUser).map(SecurityUser::getId).orElse(null);
        if (id != null) {
            if (metaObject.hasSetter("operator")) {
                metaObject.setValue("operator", null);
                this.strictUpdateFill(metaObject, "operator", Long.class, id);
            }
        }
    }
}